/**
 * 脚本作用：清理项目中没有使用过的图片
 * Author:404508644@qq.com
 * Date: 2020-01-06
 * 如何使用: cd src目录 && node clear-unused-images
 */
const fs = require('fs')
const path = require('path')
root = path.join(__dirname, 'src')

let filesCount  = 0
let hasImageFileCount = 0
let allImagesCount = 0


function getAllImages() {
  let dirName = path.resolve(__dirname, './src/assets')
  let imgEnds = ['.jpg', '.jpeg', '.gif', '.png']

  let allFiles = readFold2(dirName)

  function readFold2(path) {
    var pa = fs.readdirSync(path);
    var temp = []
    pa.forEach(function (ele, index) {
      var info = fs.statSync(path + "/" + ele)
      if (info.isDirectory()) {
        console.log("dir: " + ele)
        readFold2(path + "/" + ele);
      } else if (ele.indexOf('.png') > -1) {
        temp.push({
          name: ele,
          path: path + '/' + ele
        })
        allImagesCount++
        console.log("file: " + ele)
      }
    })

    return temp
  }

  console.log('=====================================')
  console.log('all images:' + allImagesCount)
  console.log('=====================================')
  console.log(allFiles)
  return allFiles
}

function log(v) {
  console.log(v)
}


function readFold(path) {
  var pa = fs.readdirSync(path);
  var allImages = getAllImages()

  pa.forEach(function (ele, index) {
    var info = fs.statSync(path + "/" + ele)
    if (info.isDirectory()) {
      console.log("dir: " + ele)
      readFold(path + "/" + ele);
    } else if (ele.endsWith('.vue')) {
      filesCount++
      let string = fs.readFileSync(path + '/' + ele, 'utf-8');
      allImages.forEach(v => {
        if (string.indexOf(v.name) == -1){
          fs.unlinkSync(v.path)
          console.log("删除了不用的图片: " + v.path)
        }
      })
      
    }
  })

}


readFold(root)